package bsc.war.handler;

import bsc.ejb.entity.ScoreCard;
import bsc.ejb.metadata.Comparation;
import bsc.war.delegate.DelegateBSC;
import bsc.war.factory.Factory;
import bsc.war.model.Score;
import bsc.war.service.ScoreCardUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

/**
 *
 * @author Memo
 */
public class SelectRootScoreCard extends AbstractController {

    public SelectRootScoreCard() {
    }

    @Override
    protected ModelAndView handleRequestInternal(
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        try {
            DelegateBSC delegate = (DelegateBSC) Factory.getBean("DelegateBSC");

            processRequestInternal(request, response, delegate);

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("Catched exception", e);
        }
        return new ModelAndView("drillScoreCard");
    }

    public static void processRequestInternal(HttpServletRequest request,
            HttpServletResponse response, DelegateBSC delegate) {
     

        //Find the scorecard and dimensionalCut

        Long idScoreCard = Long.parseLong(request.getParameter("scoreCard"));

        ScoreCard scoreCard = delegate.findScoreCard(idScoreCard);

        Comparation comparation = delegate.findComparation(2L);

        //System.out.println("Nombre del ScoreCard: " + scoreCard.getName());
        List<ScoreCard> scoreCardsRoot = new ArrayList<ScoreCard>();
        scoreCardsRoot.add(scoreCard);

        Map <ScoreCard, Double> scoreCardScore = new HashMap<ScoreCard, Double>();
        Map <ScoreCard, Integer> scoreCardChildren = new HashMap<ScoreCard, Integer>();
        for (ScoreCard scoreCard1 : scoreCardsRoot) {
            Score score = ScoreCardUtils.calculateScore(delegate, comparation, scoreCard1, ScoreCardUtils.getSystemDate(request));
            scoreCardScore.put(scoreCard1, score.getScore());
            scoreCardChildren.put(scoreCard1, new Integer(delegate.findScoreCard(scoreCard1).size()));

        }

        //System.out.println("Saque la lista con tamaño: " + scoreCardsRoot.size());
        request.setAttribute("parentScorecard", idScoreCard);
        request.setAttribute("scoreCardsRoot", scoreCardsRoot);
        request.setAttribute("scoreCardScore", scoreCardScore);
        request.setAttribute("scoreCardChildren", scoreCardChildren);
    }
}
